<?php

require_once(WSB_MODULES_PATH . 'sherpa/forms/Registration.php');

class Sherpa_RegistrationController extends WSB_Xtension_Extension
{

	/**
	 * @return string
	 */
	public function renderForBackend()
	{
		return get_class($this);
	}

	/**
	 * Index Action
	 */
	public function indexAction()
	{
		$this->initTranslate();

		// Eingeloggt
		$auth = WSB_Auth_Frontend::getInstance();
		if($auth->hasIdentity()) {
			$this->signedinAction();
			return;
		}

		$request = $this->getRequest();

		$buttonClicked = ($request->getPost('btnCreateAccount') != '')	// Button
		 || ($request->getPost('btnCreateAccount_x') != '')				// Image button
		 || ($request->getPost('btnCreateAccount_y') != '');			// Image button

		$form = new Sherpa_Form_Registration();
		if($request->isPost() && $buttonClicked && $form->isValid($request->getPost())) {

			// Die gefilterten Formulardaten
			$values = $form->getValues();

			// Benutzername = E-Mail
			$values['username'] = $values['email'];

			// Unbenutzte Felder loeschen
			unset($values['btnCreateAccount']);
			unset($values['confirmPassword']);

			// Erstelle neuen Benutzer
			$feuserTable = new Member_Model_DbTable_Feuser();
			$feuser = $feuserTable->createRow($values);
			$feuser->save();

			// Sende Zugangsdaten an Benutzer
			$this->assignToView($values);
			$htmlBody = $this->_view->render('registration/mail_htmlbody.phtml');

			// Konfigurationseinstellungen
			$config = $this->getConfiguration();

			$mail = new Zend_Mail();
			$mail->setBodyHtml($htmlBody);
			$mail->setBodyText(strip_tags($htmlBody));
			$mail->setSubject($this->translate('registrationEmailSubject'));
			$mail->addTo($values['email']);
			$mail->setFrom($config->senderEmail, $config->senderName);
			$mail->send();

			// Login
			if(WSB_Frontend::loginFeuser($values['username'], $values['password'])) {
				$params = array('sherpa_registration' => array('action' => 'success'));
				$url = WSB_Xtension_Url::getInstance()->getHrefToThisPage($params);
				$this->redirect($url, true);
			} else {
				$this->errorAction();
			}

		} else {

			$form->setView($this->_view);
			$this->assignToView('form', $form);
			$this->renderView('registration/index.phtml');

		}
	}

	/**
	 * Success Action
	 */
	public function successAction()
	{
		$this->renderView('registration/success.phtml');
	}

	/**
	 * Error Action
	 */
	public function errorAction()
	{
		$this->renderView('registration/error.phtml');
	}

	/**
	 * Signed In Action
	 */
	public function signedinAction()
	{
		$this->renderView('registration/signedin.phtml');
	}

}